<template>
  <Form ref='fm' :validation-schema="mySchema" v-slot="{ errors }" class="xtx-form">
    <!-- 测试 -->
    <!-- <p>{{ errors }}</p> -->
    <div class="user-info">
      <img :src="qqUser.photo" alt="" />
      <p>Hi，{{ qqUser.name }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          v-model="formData.mobile"
          :class="{ error: errors.mobile }"
          name="mobile"
          class="input"
          type="text"
          placeholder="绑定的手机号"
        />
      </div>
      <!-- 表单验证错误信息提示 -->
      <div class="error" v-show="errors.mobile">
        <i class="iconfont icon-warning" />{{ errors.mobile }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          v-model="formData.code"
          name="code"
          :class="{ error: errors.mobile }"
          class="input"
          type="text"
          placeholder="短信验证码"
        />
        <span class="code" @click="handlerCode">{{count===0?'发送验证码':`${count}秒后发送`}}</span>
      </div>
      <!-- 表单验证错误信息提示 -->
      <div class="error" v-show="errors.code">
        <i class="iconfont icon-warning" />{{ errors.code }}
      </div>
    </div>
    <a @click='bindQQ' href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import { reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'

import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'

// import { useIntervalFn } from '@vueuse/core'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { useCountDown } from '@/hooks'

import { message } from '@/components/Message/index.js'

// 获取qq头像和昵称
const useQQ = () => {
  const qqUser = ref({
    name: '',
    photo: ''
  })
  if (window.qc.Login.check()) {
    window.qc.api('get_user_info').success((res) => {
    //   console.log(res)
      qqUser.value.name = res.data.nickname
      qqUser.value.photo = res.data.figureurl_qq_1
    })
  }

  return { qqUser }
}

// 表单校验
const useValidteForm = () => {
  const formData = reactive({
    mobile: '',
    code: ''
  })

  const mySchema = {
    mobile: schema.mobile,
    code: schema.code
  }

  return { formData, mySchema }
}

// 发送验证码
const useSendCode = (formData) => {
  // 获取组件表单实例
  const fm = ref()

  // 调用倒计时方法
  const { count, start } = useCountDown(60)

  // 点击发送事件
  // 手机号格式正确才能发送点击事件发送验证码
  const handlerCode = async () => {
    // 手动校验表单某一项
    const validate = schema.mobile(formData.mobile)

    if (validate === true) {
    // 根据count是否为0,判断是否发送验证码
      if (count.value === 0) {
        try {
          await userQQBindCode(formData.mobile)
          message({ type: 'success', text: '发送成功' })
          start()
        } catch (error) {
          message({ type: 'error', text: error.response.data.message })
        }
      }
    } else {
      // 手机号码格式错误
      // 根据组件表单实例js 触发显示错误信息
      fm.value.setFieldError('mobile', validate)
    }
  }

  return { handlerCode, fm, count }
}

// qq号绑定小兔子账号
const useSubmit = (fm, props, formData) => {
  const store = useStore()
  const router = useRouter()
  const route = useRoute()

  // 点击绑定事件
  const bindQQ = async () => {
    // 整体校验
    // 绑定
    // 成功，回跳
    const res = await fm.value.validate()
    if (res.valid) {
      try {
        const { result } = await userQQBindLogin({
          unionId: props.unionId,
          ...formData
        })
        // 登陆成功存储用户信息
        await store.commit('user/setProfile', result)
        // 是否带有401的页面
        router.replace(route.query.redirect || '/')
        message({ type: 'success', text: 'qq绑定成功' })
      } catch (error) {
        message({ type: 'error', text: 'qq绑定失败' })
      }
    }
  }

  return { bindQQ }
}

export default {
  name: 'CallbackBind',

  components: {
    Form,
    Field
  },

  props: {
    unionId: {
      type: String,
      default: ''
    }
  },

  setup (props) {
    const { qqUser } = useQQ()

    const { formData, mySchema } = useValidteForm()

    const { handlerCode, fm, count } = useSendCode(formData)

    const { bindQQ } = useSubmit(fm, props, formData)

    return { qqUser, formData, mySchema, handlerCode, fm, count, bindQQ }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
